package com.nuo.backend.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.nuo.backend.common.exception.GlobalException;
import com.nuo.backend.modules.shiro.entity.SysUserTokenEntity;
import com.nuo.backend.modules.shiro.service.ShiroService;
import com.nuo.backend.modules.shiro.service.SysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description: TODO 用户信息utils
 * @author nuo
 * @date 2022/11/17 12:22
 * @version 1.0
 */
@Component
public class InfoUtils<T> {

    @Autowired
    ShiroService shiroService;

    @Autowired
    SysUserTokenService sysUserTokenService;

    /**
     * @description: 通过 token 获取用户id
     * @param token 用户的 token 令牌
     * @param identity 1: 学生  | 2: 老师
     * @return java.lang.Long id
     * @date: 2022/11/17 13:06
     */
    public Long getIdByToken(String token, Integer identity) {
        //根据accessToken，查询用户信息
        SysUserTokenEntity tokenEntity = shiroService.queryByToken(token);
        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new GlobalException("token失效，请重新登录...", 401);
        }
        SysUserTokenEntity one = sysUserTokenService.getOne(new LambdaQueryWrapper<SysUserTokenEntity>()
                .eq(SysUserTokenEntity::getIdentity, identity)
                .eq(SysUserTokenEntity::getToken, token)
        );
        return one.getUserId();
    }

    /**
     * @description: 通过 token 获取用户信息
     * @param token 用户的 token 令牌
     * @param identity 1: 学生  | 2: 老师
     * @param s xxxService
     * @return T xxxEntity.java
     * @date: 2022/11/17 12:39
     */
    public <S extends IService<T>> T getInfoByToken(String token, Integer identity, S s) {
        return s.getById(getIdByToken(token, identity));
    }

}
